package com.demo;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class BaseStationDataPreprocess {
    enum Counter
    {
        TIMESKIP,
        OUTOFTIMESKIP,
        LINESKIP,
        USERSKIP
    }

    public static class Map extends Mapper<LongWritable,Text,Text,Text> {
        String date;
        String[] timepoint;
        public void setup(Context context) throws IOException {
            this.date = context.getConfiguration().get("date");
            this.timepoint = context.getConfiguration().get("timepoint").split("-");
        }
        public void map (LongWritable key,Text value,Context context) throws IOException,InterruptedException{
            String line = value.toString();
            TableLine tableLine = new TableLine();
            try{
                tableLine.set(line,this.date,this.timepoint);
            }

            catch(Exception e)
            {
                return;
            }
            context.write(tableLine.outKey(),tableLine.outValue());


        }
    }
    public static class Reduce extends Reducer<Text,Text,NullWritable,Text> {
        private String date;
        private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        public void setup(Context context){
            this.date = context.getConfiguration().get("date");
        }
        public void reduce(Text key,Iterable<Text> values,Context context) throws IOException,InterruptedException{
            String imsi = key.toString().split("\\|")[0];//取出用户
            String timeFlag = key.toString().split("\\|")[1];//取出时间段

            TreeMap<Long,String> uploads = new TreeMap<Long,String>();//需要键值对，并关心元素的自然排序时使用
            String valueString;

            for(Text val:values)
            {
                valueString = val.toString();
                try
                {
                    uploads.put(Long.valueOf(valueString.split("\\|")[1]),valueString.split("\\|")[0]);//t放在第一个位置，position放在第二个位置
                }
                catch (NumberFormatException e )
                {
                    return;
                }
            }
            try
            {
                Date tmp = this.formatter.parse( this.date + " "+ timeFlag.split("-")[1]+":00:00" );//组合最后时间出来
                uploads.put((tmp.getTime() / 1000L), "OFF");//自己设定的一个最后时间OFF
                HashMap<String,Float> locs = getStayTime(uploads);//需要键值对表示，并不关心顺序的

                for(java.util.Map.Entry<String,Float> entry : locs.entrySet()) //使用entry进行遍历
                {
                    StringBuilder builder = new StringBuilder();
                    builder.append(imsi).append(" ");
                    builder.append(timeFlag).append(" ");
                    builder.append(entry.getKey()).append(" ");
                    builder.append(entry.getValue());
                    context.write(NullWritable.get(),new Text(builder.toString()));
                }
            }catch (Exception e){
                return;
            }
        }        //下面是计算停留时间，后一个时间减去前一个时间，如果间隔超过60分钟就认定为关机了。
        private HashMap<String,Float> getStayTime(TreeMap<Long,String> uploads){     //uploads里面是<t,position>
            java.util.Map.Entry<Long, String> upload , nextUpload ;

            HashMap<String, Float> locs = new HashMap<String,Float>();
            Iterator<java.util.Map.Entry<Long,String>> it = uploads.entrySet().iterator();
            upload = it.next();
            while(it.hasNext())
            {
                nextUpload = it.next();
                float diff = (float)(nextUpload.getKey()-upload.getKey()) / 60.0f;
                if(diff <= 60.0 )//时间间隔过大则代表关机
                {
                    if(locs.containsKey(upload.getValue()))
                        locs.put(upload.getValue(),locs.get(upload.getValue())+diff);
                    else
                        locs.put(upload.getValue(),diff);
                }
                upload = nextUpload;
            }
            return locs;
        }
    }
    public static void main( String[] args ) throws Exception
    {
        Configuration conf = new Configuration();
        conf.set("date",args[2]);
        conf.set("timepoint",args[3]);
        Job job = new Job(conf,"BaseStationDataPreprocess");
        job.setJarByClass(BaseStationDataPreprocess.class);
        job.setMapperClass(Map.class);
        job.setMapOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        //ָ指定任务的Reducer和输出的数据类型k4 v4
        job.setReducerClass(Reduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));


        job.waitForCompletion(true);


    }

}
